import { ElMessage } from "element-plus";

export default function useDown() {
  function downloadFile(res: Blob, fileName: string = "file.xlsx") {
    if (res.type === "application/json") {
      const reader = new FileReader();
      reader.onload = function (event: any) {
        const result = JSON.parse(event.target.result);
        ElMessage.error(result.msg || "下载失败");
      };
      reader.readAsText(res);
      return;
    }
    const url = window.URL.createObjectURL(res);
    const link = document.createElement("a");
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }

  function downloadUrl(url:string,fileName: string = "file.xlsx"){
    const link = document.createElement("a");
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }
  return {
    downloadFile,
    downloadUrl
  };
}
